package com.yunji.system.business;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yunji.common.base.BaseBusiness;
import com.yunji.common.base.RuoYiConfig;
import com.yunji.common.base.response.Response;
import com.yunji.common.base.response.ResponseHelper;
import com.yunji.common.constant.LogicCode;
import com.yunji.common.model.domain.CaptchaPicsDO;
import com.yunji.common.model.enums.UploadType;
import com.yunji.common.model.params.CaptchaPicsParam;
import com.yunji.common.utils.bean.BeanUtils;
import com.yunji.common.utils.file.FileUploadUtils;
import com.yunji.common.utils.file.FileUtils;
import com.yunji.system.service.CaptchaPicsService;
import com.yunji.system.service.engine.CaptchaPicsHandle;
import com.yunji.system.service.engine.CaptchaPicsValidate;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Project: yunji-coffee
 * @Package: com.yunji.common.business
 * @Title: CommonBusiness
 * <p>
 * History:
 * Date                     Version     Author          Summary
 * ============================================================
 * 2024-10-14 17:45:32      V1.0        HuaAo       新建类
 */
@Component
public class CommonBusiness extends BaseBusiness {

    @Autowired
    private CaptchaPicsService captchaService;

    @Autowired
    private CaptchaPicsValidate captchaPicsValidate;

    @Resource
    CaptchaPicsHandle ruleEngine;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.secretAccessKey}")
    private String secretAccessKey;

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;


    public Response<Map<String, Object>> upload(MultipartFile file, Integer code) {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            String fileName = "";
            String url = "";

            if (Objects.equals(UploadType.LOCAL.getCode(), code)) {
                logs.info("【通用上传】文件路径：{}", filePath);
                // 上传并返回新文件名称
                fileName = FileUploadUtils.upload(filePath, file);
                url = RuoYiConfig.getHost() + fileName;
            } else if (Objects.equals(UploadType.OSS.getCode(), code)) {
                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, secretAccessKey);
                // 上传文件路径
                logs.info("【通用上传】文件路径：{}", filePath);
                fileName = FileUploadUtils.ossUpload(filePath, file);
                fileName = fileName.replaceFirst("/", "");
                url = RuoYiConfig.getHost() + fileName;
                InputStream inputStream = null;
                inputStream = file.getInputStream();

                ossClient.putObject(bucketName, fileName, inputStream);
                ossClient.shutdown();
            }
            Map<String, Object> map = new HashMap<>();
            map.put("url", url);
            map.put("fileName", fileName);
            map.put("newFileName", FileUtils.getName(fileName));
            map.put("originalFilename", file.getOriginalFilename());
            return ResponseHelper.success(map);
        } catch (Exception e) {
            return ResponseHelper.failure(e.getMessage());
        }
    }

    public Long createCaptcha(CaptchaPicsDO captchaDO) {
        ruleEngine.handleCaptcha(captchaDO);
        return captchaService.create(captchaDO);
    }

    @Transactional
    public boolean operateCaptcha(Long picsId, Integer status) {
        CaptchaPicsDO info = captchaService.getInfo(picsId);
        Assert.isTrue(BeanUtils.isNotNull(info), "未找到验证图");

        CaptchaPicsDO picsDO = new CaptchaPicsDO();
        picsDO.setPicsId(picsId);
        picsDO.setStatus(status);

        if (Objects.equals(LogicCode.YES, status)) {
            Assert.isTrue(captchaPicsValidate.checkDelete(), "需要保留至少一张验证图");
        }
        info.setStatus(status);
        ruleEngine.handleCaptcha(info);
        // 开启 存入背景图库
        return captchaService.update(picsDO);
    }

    @Transactional
    public boolean editCaptcha(CaptchaPicsDO captchaPicsDO) {
        CaptchaPicsDO info = captchaService.getInfo(captchaPicsDO.getPicsId());
        if (captchaPicsValidate.checkUpdate(info, captchaPicsDO)) {
            info.setStatus(LogicCode.YES);
            ruleEngine.handleCaptcha(info);
        }

        if (Objects.equals(LogicCode.YES, captchaPicsDO.getStatus())) {
            Assert.isTrue(captchaPicsValidate.checkDelete(), "需要保留至少一张验证图");
        }

        ruleEngine.handleCaptcha(captchaPicsDO);
        return captchaService.update(captchaPicsDO);
    }

    public List<CaptchaPicsDO> captchaList(CaptchaPicsParam param) {
        return captchaService.pageList(param);
    }

    @Transactional
    public boolean delete(List<Long> picsIds) {
        // 必须留一个在用的
        for (Long picsId : picsIds) {
            Assert.isTrue(captchaPicsValidate.checkDelete(), "需要保留至少一张验证图");

            CaptchaPicsDO info = captchaService.getInfo(picsId);
            info.setStatus(LogicCode.NO);
            ruleEngine.handleCaptcha(info);

            captchaService.delete(picsId);


        }

        return Boolean.TRUE;
    }

    public CaptchaPicsDO getInfo(Long picsId) {
        return captchaService.getInfo(picsId);
    }
}